package app.mly.hu60;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.AllArgsConstructor;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@AllArgsConstructor
public class MessageTask {

    private final RestTemplate restTemplate;

    // 你的虎绿林用户名
    private static final String USER_NAME = "xggz";

    // 登录成功的cookie（这个是示例，需要换成自己的账号cookie）
    private static final String HU60_COOKIE = "hu60_tpl=jhin; hu60_active_captcha=xxxxxxx; hu60_sid=xxxxxxx";

    // 虎绿林地址
    private static final String HU60_HOST = "https://hu60.cn";

    // 茉莉云机器人Api
    // 获取地址：https://mly.app
    private static final String MLY_API_KEY = "";
    private static final String MLY_API_SECRET = "";

    @Scheduled(fixedDelay = 2000L)
    public void handler() {
        MultiValueMap<String,Object> param = new LinkedMultiValueMap<>();
        HttpEntity httpEntity = new HttpEntity(param, hu60Headers());

        ResponseEntity<String> response = restTemplate.exchange(HU60_HOST + "/q.php/msg.index.@.no.json?_content=text",
                HttpMethod.GET,
                httpEntity,
                String.class);

        if (HttpStatus.OK.equals(response.getStatusCode())) {
            JSONObject jsonObject = new JSONObject(response.getBody());
            JSONArray msgList = jsonObject.get("msgList", JSONArray.class);
            if (CollUtil.isEmpty(msgList)) {
                System.out.println("暂无消息" + System.currentTimeMillis());
                return;
            }
            System.out.println("收到消息：" + msgList.size() + "条");

            msgList.forEach(msgJson -> {
                JSONObject msgObj = (JSONObject) msgJson;
                Integer type = msgObj.getInt("type");
                if (type == 1) {
                    String content = msgObj.getStr("content");
                    Msg msg = jiexi(content);
                    if (StrUtil.isNotBlank(msg.getContent())) {
                        msg.setUid(msgObj.getInt("byuid"));
                        JSONObject reply = mlyReply(msg);
                        if ("00000".equals(reply.getStr("code"))) {
                            JSONArray dataArray = reply.getJSONArray("data");
                            String plugin = reply.getStr("plugin");
                            for (int i = 0; i < dataArray.size(); i++) {
                                JSONObject data = (JSONObject) dataArray.get(i);
                                Integer typed = data.getInt("typed");
                                if (typed == 1) {
                                    replyMsg(data.getStr("content"), msg, plugin);
                                } else if (typed == 2) {
                                    replyMsg("[img]https://files.molicloud.com/".concat(data.getStr("content"))+"[/img]", msg, plugin);
                                } else {
                                    replyMsg(data.getStr("remark"), msg, plugin);
                                }
                            }
                        }
                    }
                }
            });
        } else {
            System.out.println("访问错误");
        }
    }

    /**
     * 回复虎绿林消息
     *
     * @param content
     * @param msg
     * @param plugin
     */
    private void replyMsg(String content, Msg msg, String plugin) {
        MultiValueMap<String,Object> param = new LinkedMultiValueMap<>();
        HttpEntity httpEntity = new HttpEntity(param, hu60Headers());

        // 调用聊天室接口，获取发言需要的token
        ResponseEntity<String> response = restTemplate.exchange(HU60_HOST + "/q.php/" + msg.getUri(),
                HttpMethod.GET,
                httpEntity,
                String.class);
        if (HttpStatus.OK.equals(response.getStatusCode())) {
            JSONObject jsonObject = new JSONObject(response.getBody());
            String token = jsonObject.getStr("token");

            String br = "";
            if (StrUtil.isNotBlank(plugin) && !StrUtil.equals(plugin, "Chat")) {
                br = "[br]";
            }

            // 聊天室发言
            MultiValueMap<String,Object> sendParam = new LinkedMultiValueMap<>();
            sendParam.add("content", "@" + msg.getUsername() + " " + br + content);
            sendParam.add("token", token);
            sendParam.add("go", "快速发言");

            HttpEntity sendHttpEntity = new HttpEntity(sendParam, hu60Headers());

            restTemplate.exchange(HU60_HOST + "/q.php/" + msg.getUri(),
                    HttpMethod.POST,
                    sendHttpEntity,
                    String.class);
        }
    }

    /**
     * 解析虎绿林原始消息
     *
     * @param content
     * @return
     */
    private Msg jiexi(String content) {
        Msg msg = new Msg();

        Pattern pattern = Pattern.compile("(@)(.+)(\\s在\\s聊天室)(“(.+)”)(第(\\d+)楼中\\s)(http(.+)(\\s)@你：\n\n(.+))");
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            msg.setUsername(matcher.group(2));
            msg.setRoom(matcher.group(5));
            msg.setUri("addin.chat." + msg.getRoom() + ".json");

            String text = matcher.group(11);
            text = text.replace("@"+USER_NAME, "");
            text = text.replace("\r\n", "，");
            text = text.replace("\r", "，");
            text = text.replace("\n", "，");
            text = StrUtil.trim(text);
            while (true) {
                if (StrUtil.isNotBlank(text) && text.indexOf("，") == 0) {
                    text = text.substring(1);
                } else {
                    break;
                }
            }
            msg.setContent(text);
        }

        return msg;
    }

    /**
     * 调用茉莉云接口获取回复
     *
     * @param msg
     * @return
     */
    private JSONObject mlyReply(Msg msg) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("Api-Key", MLY_API_KEY);
        headers.add("Api-Secret", MLY_API_SECRET);

        JSONObject body = new JSONObject();
        body.set("content", msg.getContent());
        body.set("type", 2);
        body.set("from", msg.getUid());
        body.set("fromName", msg.getUsername());
        body.set("to", Base64.encode(msg.getRoom()));
        body.set("toName", msg.getRoom());

        HttpEntity<String> formEntity = new HttpEntity<String>(body.toString(), headers);
        return restTemplate.postForEntity("https://i.mly.app/reply", formEntity, JSONObject.class).getBody();
    }

    /**
     * 虎绿林请求头
     *
     * @return
     */
    private HttpHeaders hu60Headers() {
        List<String> cookies =new ArrayList<>();
        cookies.add(HU60_COOKIE);

        HttpHeaders headers = new HttpHeaders();
        headers.put(HttpHeaders.COOKIE, cookies);
        headers.set("user-agent", "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36");

        return headers;
    }
}